package com.example.zwlyz;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.zwlyz.models.Account;

import java.util.ArrayList;
import java.util.List;

public class AccountManager {
    private static DatabaseHelper dbHelper;

    public static void init(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    public static void addAccount(Account account) {
        dbHelper.addUser(account.getUsername(), account.getPassword());
    }

    public static List<Account> getAllAccounts() {
        List<Account> accounts = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("user", new String[]{"id", "username", "password"}, null, null, null, null, null);
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String username = cursor.getString(cursor.getColumnIndex("username"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            accounts.add(new Account(id, username, password));
        }
        cursor.close();
        db.close();
        return accounts;
    }

    public static void deleteAccount(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("user", "id = ?", new String[]{String.valueOf(id)});
        db.close();
    }

    public static boolean updatePassword(int id, String oldPassword, String newPassword) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String selection = "id = ? AND password = ?";
        String[] selectionArgs = {String.valueOf(id), oldPassword};
        ContentValues values = new ContentValues();
        values.put("password", newPassword);
        int rowsAffected = db.update("user", values, selection, selectionArgs);
        db.close();
        return rowsAffected > 0;
    }
}